package com.xiaozhen.blog.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.xiaozhen.blog.entity.Event;
import com.xiaozhen.blog.event.EventProducer;
import com.xiaozhen.blog.service.LikeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @create 2023-05-16 14:30
 */
@Controller
public class LikeController {
    @Autowired
    private LikeService likeService;

    @Autowired
    private EventProducer eventProducer;

    @RequestMapping(value = "/like", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> likePost(@RequestParam("entityType") int entityType,
                                        @RequestParam("entityId") Long entityId) throws JsonProcessingException {
        // 获取用户 id
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        int userId = Integer.parseInt(authentication.getName());
        // 点赞
        likeService.like(userId,entityType,entityId);
        // 数量
        long likeCount = likeService.findEntityLikeCount(entityType,entityId);
        // 状态
        int likeStatus = likeService.findEntityLikeStatus((long) userId, entityType, entityId);
        // 将数据传给前端页面
        Map<String,Object> map = new HashMap<>();
        map.put("likeCount",likeCount);
        map.put("likeStatus",likeStatus);

        // 点赞完，将点赞信息存入生产者
//        Event event = new Event();
//        event.setEntityType(0); // 实体类型（1 为回复）
//        event.setUserId(blogUserId); // 将要通知的用户的 id
//        event.setEntityId(comment.getId()); // 评论 id
//        event.setEntityUserId(Long.valueOf(userId)); // 发表评论的用户的 id
//        eventProducer.sendLikeMessage(event);


        return map;
    }
}
